package com.hero.herocat.handler;

import com.hero.servlet.HeroRequest;
import com.hero.servlet.HeroResponse;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 静态资源处理
 *
 * @author linhui
 */
public class StaticResourceHandler implements IHandler {
    @Override
    public boolean needHandle(String name) {
        if (name.contains(".")) {
            String suffix = name.substring(name.lastIndexOf(".") + 1);
            switch (suffix) {
                case "html":
                case "js":
                case "image":
                case "css":
                case "ico":
                    return true;
                default:
                    return false;
            }
        }


        return false;
    }

    @Override
    public void handle(HeroRequest request, HeroResponse response) throws Exception {
        URL resource = getClass().getClassLoader().getResource(request.getPath().substring(1));
        if (resource == null) {
            response.write("File not Found");
            return;
        }
        File file = new File(URLDecoder.decode(resource.getFile()));
        if (file.exists()) {
            //1. 创建输入流
            FileInputStream fis = new FileInputStream(file);
            //2. 得到一个通道
            FileChannel fc = fis.getChannel();
            //3. 准备一个缓冲区
            ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
            //4. 从通道里读取数据并存到缓冲区中
            fc.read(buffer);
            System.out.println(new String(buffer.array()));
            response.write(buffer.array());
            //5. 关闭
            fis.close();
        } else {
            response.write("File not Found");

        }


    }


}
